using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Xml.Linq;

namespace SPTraceViewUpdate
{
    public class UpdateInfo
    {
        public Version Version {get;set;}
        public string ReleaseType {get;set;}
        public string ReleaseDate {get;set;}
        public string  FileUrl {get;set;}
        public string Message {get;set;}
        public string HomeUrl {get;set;}
        public string ReleaseUrl { get; set; }
    }

    internal partial class Updater
    {
        private const string UPDATE_LOCATION = "https://sptraceview.svn.codeplex.com/svn/SPTraceView2010/";
        private string m_InstallPath = null;

        public Updater(string installPath)
        {
            m_InstallPath = installPath;
        }

        public Updater()
        {
            m_InstallPath = AppDomain.CurrentDomain.BaseDirectory;
        }

        public UpdateInfo NewUpdatesAvailable()
        {
            Trace.WriteLine("Checking for updates ...", "SPTraceView");

            Uri updateUri = new Uri(UPDATE_LOCATION + "Updates.xml");

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(updateUri);
            httpRequest.Method = "GET";
            httpRequest.Timeout = 30000; //30 sec

            HttpWebResponse response = null;

            string updateXml = null;

            try
            {
                response = (HttpWebResponse)httpRequest.GetResponse();



                Stream streamResponse = response.GetResponseStream();

                try
                {
                    using (TextReader reader = new StreamReader(streamResponse))
                    {
                        updateXml = reader.ReadToEnd();
                    }
                }
                finally
                {
                    streamResponse.Close();
                }
            }
            finally
            {
                // Close response
                if (response != null)
                    response.Close();
            }


            if (updateXml != null)
            {
                XDocument xDoc = XDocument.Parse(updateXml);

                var updateNode = from xml in xDoc.Descendants("Update")
                                 select new UpdateInfo
                                 {
                                     Version = new Version(xml.Attribute("Version").Value),
                                     ReleaseType = xml.Attribute("Type").Value,
                                     ReleaseDate = xml.Attribute("ReleaseDate").Value,
                                     FileUrl = xml.Element("File").Attribute("Path").Value,
                                     Message = xml.Element("Message").Value,
                                     HomeUrl = xml.Element("HomeUrl").Value,
                                     ReleaseUrl = xml.Element("Release").Value
                                 };

                var update = updateNode.FirstOrDefault();

                if (update != null)
                {
                    var currentVersion = CurrentlyInstalledVersion();

                    var latestVersion = update.Version;

                    Trace.WriteLine(string.Format("Current version: {0}; Published Version: {1}", currentVersion, latestVersion), "SPTraceView");
                    if (currentVersion < latestVersion)
                    {
                        return update;
                    }

                }



            }

            //try
            //{
            //    response = (HttpWebResponse)httpRequest.GetResponse();

            //    string updateXml = null;

            //    Stream streamResponse = response.GetResponseStream();

            //    try
            //    {
            //        using (TextReader reader = new StreamReader(streamResponse))
            //        {
            //            updateXml = reader.ReadToEnd();
            //        }
            //    }
            //    finally
            //    {
            //        streamResponse.Close();
            //    }

            //    if (updateXml != null)
            //    {
            //        XmlDocument xmlDoc = new XmlDocument();
            //        xmlDoc.LoadXml(updateXml);

            //        int latestVersion = CurrentlyInstalledVersion();

            //        foreach (XmlNode updateNode in xmlDoc.SelectNodes("SPTraceView/Update"))
            //        {
            //            int Version = int.Parse(updateNode.Attributes["Version"].Value);
            //            Trace.WriteLine(string.Format("Current version: {0}; Published Version: {1}", VersionToVersionString(latestVersion), VersionToVersionString(Version)), "SPTraceView");
            //            if (latestVersion < Version)
            //            {
            //                return true;
            //            }
            //        }
            //    }
            //}
            //finally
            //{
            //    // Close response
            //    if (response != null)
            //        response.Close();
            //}

            return null;
        }

        //private int VersionFromString(string version)
        //{
        //    Version v = new Version(version);
        //    return GetIntVersion(v);
        //}

        //private int GetIntVersion(Version sptvVer)
        //{
        //    return 10000 * sptvVer.Major + 1000 * sptvVer.Minor + 100 * sptvVer.Build + sptvVer.Revision;
        //}

        private Version CurrentlyInstalledVersion()
        {
            return Assembly.GetExecutingAssembly().GetName().Version;
        }

        //private int CurrentlyInstalledVersion()
        //{
        //    try
        //    {
        //        return  GetIntVersion(Assembly.GetExecutingAssembly().GetName().Version);

        //    }
        //    catch
        //    { }

        //    return 0;
        //}

        //public static string VersionToVersionString(int version)
        //{
        //    StringBuilder outVer = new StringBuilder();
        //    outVer.Append(Convert.ToString(version / 10000));
        //    outVer.Append(".");

        //    version = version % 10000;
        //    outVer.Append(Convert.ToString(version / 1000));
        //    outVer.Append(".");

        //    version = version % 1000;
        //    outVer.Append(Convert.ToString(version / 100));
        //    outVer.Append(".");
        //    outVer.Append(Convert.ToString(version % 100));

        //    return outVer.ToString();
        //}

        //public XmlNode NewUpdatesAvailable()
        //{
        //    Uri updateUri = new Uri(UPDATE_LOCATION + "Updates.xml");

        //    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(updateUri);
        //    httpRequest.Method = "GET";
        //    httpRequest.Timeout = 30000; //30 sec

        //    HttpWebResponse response = null;

        //    try
        //    {
        //        response = (HttpWebResponse)httpRequest.GetResponse();

        //        string updateXml = null;

        //        Stream streamResponse = response.GetResponseStream();

        //        try
        //        {
        //            using (TextReader reader = new StreamReader(streamResponse))
        //            {
        //                updateXml = reader.ReadToEnd();
        //            }
        //        }
        //        finally
        //        {
        //            streamResponse.Close();
        //        }

        //        if (updateXml != null)
        //        {
        //            XmlDocument xmlDoc = new XmlDocument();
        //            xmlDoc.LoadXml(updateXml);

        //            int latestVersion = CurrentlyInstalledVersion();
        //            XmlNode latestVersionNode = null;

        //            foreach (XmlNode updateNode in xmlDoc.SelectNodes("SPTraceView/Update"))
        //            {
        //                int Version = int.Parse(updateNode.Attributes["Version"].Value);
        //                if (latestVersion < Version)
        //                {
        //                    latestVersion = Version;
        //                    latestVersionNode = updateNode;
        //                }
        //            }

        //            return latestVersionNode;
        //        }
        //    }
        //    finally
        //    {
        //        // Close response
        //        if (response != null)
        //            response.Close();
        //    }

        //    return null;
        //}

       



        //private int CurrentlyInstalledVersion()
        //{
        //    if (Directory.Exists(m_InstallPath))
        //    {
        //        string sptvExeFilePath = Path.GetFullPath(m_InstallPath + "/SPTraceView.exe");
        //        if (File.Exists(sptvExeFilePath))
        //        {
        //            try
        //            {
        //                AssemblyName an = AssemblyName.GetAssemblyName(sptvExeFilePath);
        //                Version sptvVer = an.Version;
        //                return 10000 * sptvVer.Major + 1000 * sptvVer.Minor + 100 * sptvVer.Build + sptvVer.Revision;
        //            }
        //            catch
        //            { }
        //        }
        //    }
        //    else
        //    {
        //        Directory.CreateDirectory(m_InstallPath);
        //    }

        //    return 0;
        //}
    }
}
